//
//  WmcTeamSearchResultVC.swift
//  YPWatermarkCamera
//
//  Created by yupao_ios_macmini06 on 2022/9/27.
//

import MJRefresh
import UIKit

// MARK: - 扩展WmcTeamSearchResultVC + WmcNavigatorProtocol

extension WmcTeamSearchResultVC: WmcNavigatorProtocol {
    static func navigationPaths() -> [WmcNavigatorManager.Path] {
        return [.teamSearchResult]
    }

    static func willMakeNavigationVC(with parms: WmcNavigatorManager.Parms) -> UIViewController {
        var vm = WmcTeamSearchResultVM()

        if let viewModel = parms.context as? WmcTeamSearchResultVM {
            vm = viewModel
        }

        let vc = WmcTeamSearchResultVC(vm)
        return vc
    }
}

// MARK: - 扩展WmcTeamSearchResultVC + WmcVMProtocol

extension WmcTeamSearchResultVC: WmcVMProtocol {
    typealias VMType = WmcTeamSearchResultVM
}

class WmcTeamSearchResultVC: WmcBaseVC, WmcAlbumTransitionProtocol {
    // Lifecycle

    deinit {
        WmcNotificationManager.shared.removeObs(type: .deletePhotoSucceed)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        fetchData()
        
        WmcNotificationManager.shared.addObserver(type: .deletePhotoSucceed) {[weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.fetchData()
        }
    }

    // Internal

    override func makeUI() {
        makeNavView(showShadow: false)
        title = "搜索结果"

        view.backgroundColor = .wmc_grayH15_E6E6E6

        addSubview(statisticsView)
        addSubview(collectionView)

        statisticsView.addSubview(dateTitleLabel)
        statisticsView.addSubview(dateLabel)
        statisticsView.addSubview(watermarkTitleLabel)
        statisticsView.addSubview(watermarkLabel)
        statisticsView.addSubview(countLabel)
        statisticsView.addSubview(firstLine)
        statisticsView.addSubview(secondLine)

        addSubview(emptyView)

        statisticsView.snp.makeConstraints { make in
            make.top.equalTo(navView.snp.bottom).offset(8)
            make.left.right.equalToSuperview()
            make.height.equalTo(163)
        }

        dateTitleLabel.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.top.equalTo(17)
            make.height.equalTo(25)
        }

        dateLabel.snp.makeConstraints { make in
            make.right.equalTo(-16)
            make.centerY.equalTo(dateTitleLabel.snp.centerY)
            make.height.equalTo(25)
            make.width.lessThanOrEqualTo(210)
        }

        firstLine.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.top.equalTo(dateTitleLabel.snp.bottom).offset(15)
            make.right.equalTo(-16)
            make.height.equalTo(1)
        }

        watermarkTitleLabel.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.top.equalTo(firstLine.snp.bottom).offset(17)
            make.height.equalTo(25)
        }

        watermarkLabel.snp.makeConstraints { make in
            make.right.equalTo(-16)
            make.centerY.equalTo(watermarkTitleLabel.snp.centerY)
            make.height.equalTo(25)
            make.width.lessThanOrEqualTo(210)
        }

        secondLine.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.top.equalTo(watermarkTitleLabel.snp.bottom).offset(15)
            make.right.equalTo(-16)
            make.height.equalTo(1)
        }

        countLabel.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.top.equalTo(secondLine.snp.bottom).offset(17)
        }

        collectionView.snp.makeConstraints { make in
            make.top.equalTo(statisticsView.snp.bottom)
            make.left.right.bottom.equalToSuperview()
        }

        emptyView.snp.makeConstraints { make in
            make.top.left.right.bottom.equalTo(collectionView)
        }

        var dateStr = ""
        if let startDate = viewModel.startDate {
            dateStr.append(startDate)
        }

        if let endDate = viewModel.endDate {
            dateStr.append(" 至 ")
            dateStr.append(endDate)
        }

        dateLabel.text = dateStr

        var text = "未选择"
        if !viewModel.watermarks.isEmpty {
            var titles: [String] = []
            viewModel.watermarks.forEach { model in
                titles.append(model.data.name)
            }
            text = titles.joined(separator: "，")
        }
        watermarkLabel.text = text
    }

    override func bindViewAction() {
        collectionView.mj_header = MJRefreshNormalHeader(refreshingBlock: { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.fetchData(showLoading: false)
        })

        collectionView.mj_footer = MJRefreshBackNormalFooter(refreshingBlock: { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.loadMore()
        })
    }

    override func bindViewModel() {}

    // Private

    private lazy var statisticsView: UIView = {
        let view = UIView()
        view.backgroundColor = .wmc_white_FFFFFF
        return view
    }()

    private lazy var dateTitleLabel: UILabel = {
        let label = UILabel()
        label.textColor = .wmc_grayH2_323233
        label.font = 17.wmc_font
        label.text = "拍摄时间"
        return label
    }()

    private lazy var dateLabel: UILabel = {
        let label = UILabel()
        label.textColor = .wmc_grayH5_606066
        label.textAlignment = .right
        label.font = 17.wmc_font
        return label
    }()

    private lazy var watermarkTitleLabel: UILabel = {
        let label = UILabel()
        label.textColor = .wmc_grayH2_323233
        label.font = 17.wmc_font
        label.text = "水印"
        return label
    }()

    private lazy var watermarkLabel: UILabel = {
        let label = UILabel()
        label.textColor = .wmc_grayH5_606066
        label.textAlignment = .right
        label.font = 17.wmc_font
        return label
    }()

    private lazy var countLabel: UILabel = {
        let label = UILabel()
        label.textColor = .wmc_grayH2_323233
        label.font = UIFont.systemFont(ofSize: 18, weight: .semibold)
        label.text = "共搜到：0张照片"
        return label
    }()

    private lazy var firstLine: UIView = {
        let view = UIView()
        view.backgroundColor = .wmc_grayH19_F5F5F5
        return view
    }()

    private lazy var secondLine: UIView = {
        let view = UIView()
        view.backgroundColor = .wmc_grayH19_F5F5F5
        return view
    }()

    private lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        let width = (self.view.bounds.width - 38) / 3.0
        layout.itemSize = CGSize(width: width, height: width)
        layout.minimumLineSpacing = 3
        layout.minimumInteritemSpacing = 3
        layout.sectionInset = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 16)
        layout.sectionHeadersPinToVisibleBounds = false

        let collectView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
        collectView.backgroundColor = .wmc_white_FFFFFF
        collectView.delegate = self
        collectView.dataSource = self
        collectView.showsVerticalScrollIndicator = true
        collectView.register(WmcCloudPhotoCell.self, forCellWithReuseIdentifier: "WmcCloudPhotoCell")
        return collectView
    }()

    private lazy var emptyView: WmcCloudAllPhotoEmptyView = {
        let view = WmcCloudAllPhotoEmptyView()
        view.isHidden = true
        return view
    }()

    private func fetchData(showLoading: Bool = true) {
        if showLoading {
            WmcHudManager.loading()
        }

        viewModel.refresh { [weak self] list in
            guard let weakSelf = self else { return }
            if showLoading {
                WmcHudManager.dismiss()
            }

            weakSelf.emptyView.isHidden = !list.isEmpty
            weakSelf.collectionView.reloadData()
            weakSelf.collectionView.mj_header?.endRefreshing()

            if weakSelf.viewModel.hasNoMore {
                weakSelf.collectionView.mj_footer?.endRefreshingWithNoMoreData()
            } else {
                weakSelf.collectionView.mj_footer?.resetNoMoreData()
            }

            weakSelf.countLabel.text = "共搜到：\(weakSelf.viewModel.total)张照片"
            weakSelf.countLabel.isHidden = weakSelf.viewModel.total == 0

        } failure: { [weak self] _ in
            guard let weakSelf = self else { return }
            if showLoading {
                WmcHudManager.dismiss()
            }
            weakSelf.collectionView.mj_header?.endRefreshing()
            WmcHudManager.toast("网络不佳，请稍后再试")
        }
    }

    private func loadMore() {
        viewModel.loadMore { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.collectionView.reloadData()
            if weakSelf.viewModel.hasNoMore {
                weakSelf.collectionView.mj_footer?.endRefreshingWithNoMoreData()
            } else {
                weakSelf.collectionView.mj_footer?.endRefreshing()
            }
        } failure: { [weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.collectionView.mj_footer?.endRefreshing()
            WmcHudManager.toast("网络不佳，请稍后再试")
        }
    }
}

// MARK: - UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout

extension WmcTeamSearchResultVC: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    func numberOfSections(in _: UICollectionView) -> Int {
        return 1
    }

    func collectionView(_: UICollectionView, numberOfItemsInSection _: Int) -> Int {
        return viewModel.dataSource.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "WmcCloudPhotoCell", for: indexPath) as! WmcCloudPhotoCell
        if let model = viewModel.dataSource.yp.object(at: indexPath.row) {
            cell.bindModel(model)
        }
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        guard let _ = collectionView.cellForItem(at: indexPath) as? WmcCloudPhotoCell else { return }
        tabBarController?.tabBar.isHidden = true
        if indexPath.row < viewModel.browserDataSource.count {
            guard let album = viewModel.teamAblum, let model = viewModel.dataSource.yp.object(at: indexPath.row) else {
                return
            }
            let browser = WmcTeamAlbumBrowser(album: album,
                                              browserDataSource: viewModel.browserDataSource,
                                              originalDataSource: viewModel.dataSource)
            browser.browserPhotos(model: model)
        }
    }
}
